/**
 * 创建本地缓存对象
 * @param {string=} prefixKey
 */
export const createStorage = (prefixKey = "") => {
	/**
	 * 本地缓存类
	 * @class Storage
	 */
	const Storage = class {
		getKey(key) {
			return `${prefixKey}${key}`
		}
		/**
		 * @description 设置缓存
		 * @param {string} key 缓存键
		 * @param {*} value 缓存值
		 */
		set(key, value) {
			const stringData = JSON.stringify({
				value,
			})
			uni.setStorageSync(this.getKey(key), stringData)
		}

		/**
		 * 读取缓存
		 * @param {string} key 缓存键
		 * @param {*=} def 默认值
		 */
		get(key, def = null) {
			const item = uni.getStorageSync(this.getKey(key))
			if (item) {
				try {
					const data = JSON.parse(item)
					const { value } = data
					return value
				} catch (e) {
					return def
				}
			}
			return def
		}

		/**
		 * 从缓存删除某项
		 * @param {string} key
		 */
		remove(key) {
			uni.removeStorageSync(this.getKey(key))
		}

		/**
		 * 清空所有缓存
		 * @memberOf Cache
		 */
		clear() {
			uni.clearStorageSync()
		}
	}
	return new Storage()
}

export const storage = createStorage()
